package com.fh.service.impl;

import com.fh.model.ProductSearch;
import com.fh.model.Products;
import com.fh.service.SearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public Object getProductByKey(Products products) {
        Pageable pageable= PageRequest.of(products.getPage(),products.getSize());
        NativeSearchQuery nativeSearchQuery=new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.queryStringQuery(products.getKey()))
                .withPageable(pageable)
                .build();
        SearchHits<ProductSearch> search = elasticsearchRestTemplate.search(nativeSearchQuery, ProductSearch.class);
        List productModelList=new ArrayList();
            search.getSearchHits().forEach(searchHit->{
                productModelList.add(searchHit.getContent());

            });
            products.setData(productModelList);
            products.setTotal(search.getTotalHits());

         return products;
    }

    @Override
    public  ProductSearch  getProductDetail(String productId) {
        return elasticsearchRestTemplate.get(productId, ProductSearch.class);
    }
}
